// pages/my/chat/chatDetail.js
const { messageAPI } = require('../../../utils/api');

Page({
	data: {
		InputBottom: 0,
		userInfo: {
			avatarUrl: "https://ossweb-img.qq.com/images/lol/web201310/skin/big107000.jpg",
			nickName: "张角",
		},
		lawyerInfo: {
			name: "",
			avatar: "https://ossweb-img.qq.com/images/lol/web201310/skin/big143004.jpg"
		},
		msgList: [],
		orderId: "",
		inputContent: "",
		pageNum: 1,
		pageSize: 20,
		hasMore: true,
		loading: false
	},

	onLoad(options) {
		if (options.orderId) {
			this.setData({
				orderId: options.orderId,
				'lawyerInfo.name': options.lawyerName || "律师"
			});
			wx.setNavigationBarTitle({
				title: this.data.lawyerInfo.name,
			})
			this.loadChatHistory(true);
			this.markMessagesAsRead(options.orderId);
		}
	},

	markMessagesAsRead(orderId) {
		messageAPI.read(orderId).then(() => {
			console.log(`Conversation ${orderId} marked as read.`);
		}).catch(err => {
			console.error('标记已读失败:', err);
		});
	},

	loadChatHistory(refresh = false) {
		if (this.data.loading) return;
		if (!refresh && !this.data.hasMore) return;

		this.setData({ loading: true });
		
		const params = {
			orderId: this.data.orderId,
			pageNum: this.data.pageNum,
			pageSize: this.data.pageSize
		};

		messageAPI.list(params).then(res => {
			const newMessages = res.data.list || [];
			const list = refresh ? newMessages.reverse() : this.data.msgList.concat(newMessages.reverse());
			
			// Map to old field names for template compatibility
			const formattedList = list.map(item => ({
				...item,
				chatContent: item.content,
				chatTime: this.formatTime(item.createTime)
			}));

			this.setData({
				msgList: formattedList,
				pageNum: this.data.pageNum + 1,
				hasMore: newMessages.length === this.data.pageSize,
				loading: false
			});
		}).catch(err => {
			this.setData({ loading: false });
			wx.showToast({ title: err.message || '加载失败', icon: 'none' });
		});
	},

	sendMessage() {
		if (!this.data.inputContent.trim()) {
			return;
		}

		const content = this.data.inputContent;
		this.setData({ inputContent: "" });

		messageAPI.send(this.data.orderId, content).then(res => {
			const newMessage = res.data;
			// Map to old field names for template compatibility
			const formattedMessage = {
				...newMessage,
				chatContent: newMessage.content,
				chatTime: this.formatTime(newMessage.createTime)
			};
			this.setData({
				msgList: [...this.data.msgList, formattedMessage]
			});
		}).catch(err => {
			wx.showToast({ title: err.message || '发送失败', icon: 'none' });
		});
	},

	InputFocus(e) {
		this.setData({ InputBottom: e.detail.height });
	},

	InputBlur(e) {
		this.setData({ InputBottom: 0 });
	},

	onInputChange(e) {
		this.setData({ inputContent: e.detail.value });
	},

	formatTime(dateString) {
		if (!dateString) return '';
		const date = new Date(dateString);
		const hours = date.getHours().toString().padStart(2, '0');
		const minutes = date.getMinutes().toString().padStart(2, '0');
		return `${hours}:${minutes}`;
	}
});
